package com.qianwei.footpath.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.widget.EditText;
import android.widget.TextView;

import com.common.baselib.mvp.MvpBasePresenter;
import com.common.baselib.ui.ToastUtil;
import com.hjq.shape.view.ShapeTextView;
import com.qianwei.footpath.R;
import com.qianwei.footpath.base.BaseActivity;
import com.qianwei.footpath.bean.LocalConfigBean;
import com.qianwei.footpath.event.SerialPortEvent;
import com.qianwei.footpath.manage.LocalCacheDataManage;
import com.qianwei.footpath.manage.SerialPortManager;
import com.qianwei.footpath.utils.Constants;
import com.qianwei.footpath.utils.MemoryUtils;
import com.qianwei.footpath.utils.Util;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class ConfigActivity extends BaseActivity {
    private LocalConfigBean localConfigBean;
    private EditText etUrl, etImei, physical_test_timeout, etBalanceForce;
    private TextView tvInfo;

    @Override
    protected int layoutId() {
        return R.layout.activity_config;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);

        localConfigBean = LocalCacheDataManage.getLocalConfigData();

        tvInfo = findViewById(R.id.tvInfo);
        etUrl = findViewById(R.id.etUrl);
        etImei = findViewById(R.id.etImei);
        physical_test_timeout = findViewById(R.id.physical_test_timeout);
        etBalanceForce = findViewById(R.id.etBalanceForce);

        etUrl.setText(localConfigBean.getServerUrl());
        etImei.setText(localConfigBean.getImei());
        physical_test_timeout.setText(String.valueOf(localConfigBean.getPhysical_test_timeout()));
        etBalanceForce.setText(String.valueOf(localConfigBean.getBalance_force()));

        TextView tv_close = findViewById(R.id.tv_close);
        TextView tv_save = findViewById(R.id.tv_save);
        tv_save.setOnClickListener(v -> {
            saveData();
            ToastUtil.showToastShort(getContext(), "保存成功！");
            finish();
        });
        tv_close.setOnClickListener(v -> {
            finish();
        });


        setSystemInfo();

        etBdHeight = findViewById(R.id.etBdHeight);
        bdHeight = findViewById(R.id.bdHeight);
        testHeight = findViewById(R.id.testHeight);
        etBdWeight = findViewById(R.id.etBdWeight);
        bdWeight = findViewById(R.id.bdWeight);
        qupi = findViewById(R.id.qupi);
        testWeight = findViewById(R.id.testWeight);
        czWeight = findViewById(R.id.czWeight);

        bdHeight.setOnClickListener(v -> {
            //标定身高
            String value = etBdHeight.getText().toString();
            if (TextUtils.isEmpty(value)) {
                ToastUtil.showToastLong(getContext(), "请输入标定值！");
                return;
            }
            int intValue = Integer.parseInt(value);
            if (SerialPortManager.getInstance(getContext()).openPort()) {
                SerialPortManager.getInstance(getContext()).sendGenerateHeightCalibrationCommand(intValue);
            }
        });

        testHeight.setOnClickListener(v -> {
            //测试身高
            if (SerialPortManager.getInstance(getContext()).openPort()) {
                SerialPortManager.getInstance(getContext()).sendHeightCommand();
            }
        });

        qupi.setOnClickListener(v -> {
            //去皮重
            if (SerialPortManager.getInstance(getContext()).openPort()) {
                SerialPortManager.getInstance(getContext()).setPeelWeight(true);
                SerialPortManager.getInstance(getContext()).sendTareCommand();
            }
        });

        czWeight.setOnClickListener(v -> {
            //称重
            if (SerialPortManager.getInstance(getContext()).openPort()) {
                SerialPortManager.getInstance(getContext()).sendRealTimeWeightCommand();
            }
        });

        bdWeight.setOnClickListener(v -> {
            //标定体重
            String value = etBdWeight.getText().toString();
            if (TextUtils.isEmpty(value)) {
                ToastUtil.showToastLong(getContext(), "请输入标定值！");
                return;
            }
            float intValue = Float.parseFloat(value);

            if (SerialPortManager.getInstance(getContext()).openPort()) {
                SerialPortManager.getInstance(getContext()).sendCalibrateWeightCommand(intValue);
            }
        });

        testWeight.setOnClickListener(v -> {
            //测试体重
            if (SerialPortManager.getInstance(getContext()).openPort()) {
                SerialPortManager.getInstance(getContext()).sendWeightCommand();
            }
        });
    }

    private EditText etBdHeight, etBdWeight;
    private ShapeTextView bdHeight, testHeight, bdWeight, qupi, testWeight, czWeight;

    @Override
    protected MvpBasePresenter createPresenter() {
        return null;
    }

    private void saveData() {
        String url = etUrl.getText().toString();

        localConfigBean.setServerUrl(!TextUtils.isEmpty(url) ? url : Constants.SERVER_URL);
        String physicalTestTimeout = physical_test_timeout.getText().toString();
        localConfigBean.setPhysical_test_timeout(!TextUtils.isEmpty(physicalTestTimeout) ? Integer.parseInt(physicalTestTimeout) : 30);

        String balanceForce = etBalanceForce.getText().toString();
        localConfigBean.setBalance_force(!TextUtils.isEmpty(balanceForce) ? Integer.parseInt(balanceForce) : 20);

        LocalCacheDataManage.setLocalConfigData(localConfigBean);

    }

    private void setSystemInfo() {
        String[] versionInfo = Util.getAppVersionInfo(getContext());
        String availableMemory = MemoryUtils.getAvailableMemory();

        if (versionInfo == null || versionInfo.length < 2) {
            return;
        }

        String fullText = "版本号：" + versionInfo[1] + "(" + versionInfo[0] + ")" + " 可用内存：" + availableMemory;

        SpannableString spannableString = new SpannableString(fullText);

        int versionStart = fullText.indexOf("版本号：") + "版本号：".length();
        int versionEnd = fullText.indexOf(" 可用内存：");
        spannableString.setSpan(
                new ForegroundColorSpan(Color.RED), // 红色
                versionStart, versionEnd, // 版本号部分的起始和结束位置
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE // 标志
        );

        int memoryStart = fullText.indexOf("可用内存：") + "可用内存：".length();
        int memoryEnd = fullText.length();
        spannableString.setSpan(
                new ForegroundColorSpan(Color.RED), // 红色
                memoryStart, memoryEnd, // 可用内存部分的起始和结束位置
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE // 标志
        );

        tvInfo.setText(spannableString);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRealTimeWeightReceived(SerialPortEvent.RealTimeWeightEvent event) {
        ToastUtil.showToastLong(getContext(), "测量完成:" + Util.roundToOneDecimal(event.value) + "KG");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWeightCompletion(SerialPortEvent.WeightCompletionEvent event) {
        ToastUtil.showToastLong(getContext(), "测量完成:" + Util.roundToOneDecimal(event.finalValue) + "KG");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHeightCompletion(SerialPortEvent.HeightCompletionEvent event) {
        ToastUtil.showToastLong(getContext(), "测量完成:" + Util.roundToOneDecimal(event.finalValue) + "cm");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onError(SerialPortEvent.ErrorEvent event) {
        ToastUtil.showToastLong(getContext(), "报错：" + event.message);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onProtocolError(SerialPortEvent.ProtocolErrorEvent event) {
        ToastUtil.showToastLong(getContext(), "报错：errorCode=" + event.errorCode + ",errorMsg=" + event.errorMsg);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPeelWeightComplete(SerialPortEvent.PeelWeightCompleteEvent event) {
        SerialPortManager.getInstance(getContext()).setPeelWeight(false);
        ToastUtil.showToastLong(getContext(), "去皮重完成");
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        SerialPortManager.getInstance(getContext()).release();
        super.onDestroy();
    }
}
